package com.ddxz.tool.core.convert;

import com.ddxz.tool.core.exception.DdxzBaseException;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

import static com.ddxz.tool.core.exception.DdxzErrorStatus.INVALID_VERSION;

/**
 * @author 朱宗刚
 * @version 1.0.0
 * @description com.casic.exchange.com.casic.common.tools.convert.VersionUtil
 * @date 2020/2/28
 */

@Slf4j
public class VersionUtil {
    public static String verToStr(int version) {
        int major = (version & 0xFF000000) >> 24;
        int minor = (version & 0x00FFF000) >> 16;
        int litter = version & 0x00000FFF;

        return String.format("%d.%d.%d", major, minor, litter);
    }

    public static int strToVer(String version) {
        List<String> ver = StringUtil.getList(version, "\\.");
        if(ver.size() != VERSION_PART) {
            return 0;
        }

        try {
            return StringUtil.toInteger(ver.get(0)) << 24
                    | StringUtil.toInteger(ver.get(1)) << 16
                    | StringUtil.toInteger(ver.get(2));
        } catch (Exception e) {
            log.error(INVALID_VERSION.getMessage(), e);
            throw new DdxzBaseException(INVALID_VERSION, version);
        }
    }

    public static boolean isVersion(String version) {
        List<String> ver = StringUtil.getList(version, "\\.");
        if(ver.size() != VERSION_PART) {
            return false;
        }

        return true;
    }

    public static int riseVersion(int version) {
        return riseVersion(version, DEFAULT_STEP);
    }

    public static int riseVersion(int version, int step) {
        return version + step;
    }

    public static int versionRise(String version) {
        return versionRise(version, DEFAULT_STEP);
    }

    public static int versionRise(String version, int step) {
        try {
            return riseVersion(strToVer(version), step);
        } catch (Exception e) {
            log.error(INVALID_VERSION.getMessage(), e);
            throw new DdxzBaseException(INVALID_VERSION, version);
        }
    }

    public static String riseVersion(String version, int step) {
        return verToStr(step + strToVer(version));
    }

    public static String riseVersion(String version) {
        return riseVersion(version, 1);
    }

    private static final int VERSION_PART = 3;
    private static final int DEFAULT_STEP = 1;
}
